<template>
  <div class="main">
    <el-card>
      <el-steps :active="step" finish-status="success">
        <el-step title="商品基本信息" />
        <el-step title="添加库存信息" />
        <el-step title="添加到移动端详情" />
      </el-steps>
    </el-card>

    <el-card style="margin:30px;width:100%">
      <el-form :model="formInline" :rules="rules" :inline="true" class="demo-form-inline">
        <div v-show="step == 1">
          <div class="title">基本信息</div>
          <el-row type="flex" justify="space-between">
            <el-form-item label="商品名称" size="mini" prop="name">
              <el-input v-model="formInline.name" placeholder="商品名称" />
            </el-form-item>
            <el-form-item label="商品编号" size="mini">
              <el-input v-model="formInline.productSn " placeholder="商品编号" />
            </el-form-item>
            <el-form-item label="商品分类" size="mini">
              <el-select v-model="formInline.productCategoryId" placeholder="商品分类">
                <el-option v-for="item in categoryList" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item label="商品品牌" size="mini">
              <el-select v-model="formInline.brandId" placeholder="商品品牌">
                <el-option v-for="item in brandList" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-row>
          <el-row type="flex" justify="start">
            商品描述<el-input v-model="formInline.description" size="small" type="textarea" :rows="2" placeholder="请输入内容" style="width:50%;margin-left:10px" />
          </el-row>
          <div class="title">商品属性</div>
          <el-row type="flex" justify="space-between">
            <el-form-item label="商品原价" size="mini">
              <el-input-number v-model="formInline.originalPrice" :min="0" />
            </el-form-item>
            <el-form-item label="促销类型" size="mini">
              <el-input-number :disabled="true" :min="0" />
            </el-form-item>
            <el-form-item label="活动价格" size="mini">
              <el-input-number :disabled="true" :min="0" />
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item label="重量(kg)" size="mini">
              <el-input-number v-model="formInline.weight" :min="0" />
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item label="审核状态" size="mini">
              <el-switch v-model="formInline.verifyStatus" :inactive-value="0" :active-value="1" />
            </el-form-item>
            <el-form-item label="是否上架" size="mini" style="margin-left:260px">
              <el-switch v-model="formInline.publishStatus" :inactive-value="0" :active-value="1" />
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item label="略缩图" size="mini">
              <el-upload
                class="avatar-uploader"
                :action="action"
                :headers="headers"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
              >
                <img v-if="formInline.pic" :src="formInline.pic" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon" />
              </el-upload>
            </el-form-item>
          </el-row>

          <div class="title">其他信息</div>
          <el-row type="flex" justify="space-between">
            <el-form-item label="推荐状态" size="mini">
              <el-switch v-model="formInline.recommendStatus" :inactive-value="0" :active-value="1" />
            </el-form-item>
            <el-form-item label="新品状态" size="mini">
              <el-switch v-model="formInline.newStatus" :inactive-value="0" :active-value="1" />
            </el-form-item>
            <el-form-item label="预告商品" size="mini">
              <el-switch v-model="formInline.previewStatus" :inactive-value="0" :active-value="1" />
            </el-form-item>
          </el-row>
          <el-row type="flex" justify="space-between">
            <el-form-item label="搜索关键词" size="mini">
              <el-input v-model="formInline.keywords" placeholder="关键词" />
            </el-form-item>
            <el-form-item label="库存预警" size="mini">
              <el-input-number v-model="formInline.lowStock" :min="0" />
            </el-form-item>
            <el-form-item label="商品排序" size="mini">
              <el-input-number v-model="formInline.sort" :min="0" />
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item label="产品排序" size="mini">
              <el-checkbox-group v-model="serviceIds">
                <el-checkbox label="1" name="type">无忧退货</el-checkbox>
                <el-checkbox label="2" name="type">快速退款</el-checkbox>
                <el-checkbox label="3" name="type">免费包邮</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-row>
        </div>
        <!-- 下一步，第二页 -->
        <div v-show="step === 2">

          <div slot="header" class="clearfix">
            <span>商品SKU信息</span>
          </div>
          <el-form :inline="true">
            <el-row :gutter="30">
              <el-col :span="8">
                <el-form-item label="标题">
                  <el-input v-model="formInline.detailTitle" placeholder="标题" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="副标题">
                  <el-input v-model="formInline.detailDesc" placeholder="副标题" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-form-item label="画册图片">
              <el-upload
                :action="action"
                :headers="headers"
                :limit="5"
                :file-list="fileList"
                list-type="picture-card"
                :on-success="handleImgSuccess"
                :on-remove="handleRemove"
              >
                <i class="el-icon-plus" />
                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb,文件不超过5个</div>
              </el-upload>
            </el-form-item>

            <el-form-item label="sku设置" style="width:100%">
              <div v-show="colorArr.length>0" style="display:flex">
                <div>颜色：</div>
                <el-checkbox-group v-model="checkColor">
                  <el-checkbox v-for="(item,index) in colorArr" :key="index" :label="item">
                    <span>{{ item }}</span>
                    <el-button type="text" style="color:#f00;margin-left:4px" size="mini" @click="del(item)">删除</el-button>
                  </el-checkbox>
                </el-checkbox-group>
              </div>
              <div v-show="sizeArr.length>0" style="display:flex">
                <div>大小：</div>
                <el-checkbox-group v-model="checkSize">
                  <el-checkbox v-for="(item,index) in sizeArr" :key="index" :label="item">
                    <span>{{ item }}</span>
                    <el-button type="text" style="color:#f00;margin-left:4px" size="mini" @click="delSize(item)">删除</el-button>
                  </el-checkbox>
                </el-checkbox-group>
              </div>
              <div class="sku">
                <div class="sku-left">
                  <div class="items">
                    <el-input v-model="color" placeholder="颜色描述：比如土豪金" size="mini" />
                    <el-button size="mini" @click="addColor">创建颜色选项</el-button>
                  </div>
                  <div class="items">
                    <el-input v-model="size" placeholder="大小" size="mini" />
                    <el-button size="mini" @click="addSize">创建大小选项</el-button>
                  </div>
                </div>
                <div class="btns">
                  <el-button type="primary" size="mini" @click="createSku">生成sku列表</el-button>
                  <el-button type="primary" size="mini" @click="addSku">新增sku</el-button>
                </div>
              </div>
              <!-- 生成sku表格 -->
              <div v-show="skuArr.length>0">
                <el-table
                  :data="skuArr"
                  border
                  style="width: 100%"
                >
                  <el-table-column
                    type="index"
                    label="#"
                    fixed="left"
                    align="center"
                  />
                  <el-table-column label="图片" prop="pic" width="120" align="center">
                    <template slot-scope="scope">
                      <el-upload
                        class="avatar-uploader"
                        :action="action"
                        :headers="headers"
                        :show-file-list="false"
                        :on-success="handlePicSuccess"
                        @click.native="selectRow(scope.row)"
                      >
                        <img v-if="scope.row.pic" :src="scope.row.pic" class="avatar">
                        <i v-else class="el-icon-plus avatar-uploader-icon" />
                      </el-upload>
                    </template>
                  </el-table-column>
                  <el-table-column label="颜色" width="160" align="center">
                    <template slot-scope="scope">
                      <el-input v-model="scope.row.spData[0].value" size="mini" />
                    </template>
                  </el-table-column>
                  <el-table-column label="库存" width="160" align="center">
                    <template slot-scope="scope">
                      <el-input v-model="scope.row.stock " size="mini" placeholder="自定义库存" />
                    </template>
                  </el-table-column>
                  <el-table-column label="预警库存" width="160" align="center">
                    <template slot-scope="scope">
                      <el-input v-model="scope.row.lowStock " size="mini" placeholder="预警库存" />
                    </template>
                  </el-table-column>
                  <el-table-column label="锁定库存" width="160" align="center">
                    <template slot-scope="scope">
                      <el-input v-model="scope.row.lockStock " size="mini" placeholder="锁定库存" />
                    </template>
                  </el-table-column>
                  <el-table-column label="sku编码" width="160" align="center">
                    <template slot-scope="scope">
                      <el-input v-model="scope.row.skuCode " size="mini" placeholder="sku编码" />
                    </template>
                  </el-table-column>
                  <el-table-column label="价格" width="160" align="center">
                    <template slot-scope="scope">
                      <el-input v-model="scope.row.price " size="mini" placeholder="价格" />
                    </template>
                  </el-table-column>
                  <el-table-column label="销量" width="160" align="center">
                    <template slot-scope="scope">
                      <el-input v-model="scope.row.sale " size="mini" placeholder="销量" />
                    </template>
                  </el-table-column>
                  <el-table-column
                    fixed="right"
                    label="操作"
                    width="80"
                    align="center"
                  >
                    <template slot-scope="scope">
                      <el-button type="text" size="small" style="color:#f00" @click="delRow(scope.row)">删除</el-button>
                    </template>
                  </el-table-column>

                </el-table>
              </div>

            </el-form-item>

          </el-form>

        </div>
        <div v-show="step === 3">
          <div slot="header" class="clearfix">
            <span>详情描述</span>
          </div>
          <div class="main">
            <Tinymce ref="Tin" />
          </div>
          <div class="note" style="display:flex;jusity-content:center;align-items:center;margin-top:20px">
            <div style="font-size:14px;margin-right:10px">备注</div>
            <el-input
              v-model="formInline.note"
              type="textarea"
              :rows="2"
              placeholder="备注"
              style="width:95%"
            />
          </div>
        </div>
      </el-form>

      <el-row type="flex" justify="center" style="margin-top:30px">
        <el-button v-if="step>1" size="mini" @click="back">返回上一步</el-button>
        <el-button v-if="step<3" type="primary" size="mini" @click="next">下一步</el-button>
        <el-button v-if="step==3" type="primary" size="mini" @click="submit">提交保存</el-button>
      </el-row>

    </el-card>
  </div>
</template>
<script>
import { getToken } from '@/utils/myAuth'
import { findAllBrand } from '@/api/market/activity'
import { getAllCategory, addProductAndSkus, updateProductAndSkus, productSkusDetail } from '@/api/product/product'
import Tinymce from '@/components/Tinymce'
import { v4 as uuidv4 } from 'uuid'
export default {
  components: {
    Tinymce
  },
  data() {
    return {
      rules: {
        name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ]
      },
      id: '',
      step: 1,
      brandList: [],
      categoryList: [],
      formInline: {
        name: '',
        productSn: '',
        brandId: '',
        productCategoryId: '',
        description: '',
        originalPrice: '',
        weight: '',
        verifyStatus: '',
        publishStatus: '',
        recommendStatus: '',
        newStatus: '',
        previewStatus: '',
        keywords: '',
        sort: '',
        lowStock: '',
        pic: '',
        detailTitle: '',
        detailDesc: '',
        note: '' // 备注
      },
      serviceIds: [],
      action: '/lejuAdmin/material/uploadFileOss', // 图片上传地址
      fileList: [], // 上传图片文件
      color: '',
      size: '',
      colorArr: [],
      sizeArr: [],
      checkColor: [], // 选中的颜色列表
      checkSize: [], // 选中的大小规格
      skuArr: [], // sku表格数组
      currentRow: {}

    }
  },

  computed: {
    headers() {
      const token = getToken()
      return {
        token
      }
    }
  },
  created() {
    findAllBrand().then(res => {
      // console.log(res)
      this.brandList = res.data.items
    })
    getAllCategory().then(res => {
      res.data.items.forEach(ele => {
        if (ele.category.name === '乐居') {
          this.categoryList = ele.children
          // console.log(this.categoryList)
        }
      })
    })
    // 有ID,编辑
    this.id = this.$route.params.id
    if (this.id) {
      this.getProductDetail(this.id)
    }
  },
  methods: {
    getProductDetail(data) {
      productSkusDetail(data).then(res => {
        console.log(res)
        this.formInline = res.data.product

        if (this.formInline.serviceIds.length > 0) {
          this.serviceIds = this.formInline.serviceIds.split(',')
        }
        // 图片
        if (this.formInline.albumPics) {
          var imgdata = this.formInline.albumPics.split(',')
          imgdata.forEach(item => {
            this.fileList.push({ url: item })
          })
        }
        // 富文本赋值
        this.setTin(this.formInline.detailMobileHtml)

        // sku列表
        res.data.skus.forEach(item => {
          this.skuArr.push({
            ...item,
            spData: JSON.parse(item.spData)
          })
        })
      })
    },
    back() {
      this.step--
    },
    next() {
      this.step++
    },
    handleAvatarSuccess(res, file) {
      if (res.success) {
        this.formInline.pic = res.data.fileUrl
      } else {
        this.$message.error('图片上传失败')
      }
    },
    handleImgSuccess(res, file) {
      // console.log(res)
      if (res.success) {
        this.fileList.push({ url: res.data.fileUrl })
        this.$message.success('上传成功')
      } else {
        this.$message.error('上传失败')
      }
    },
    handleRemove(res, file) {
      this.fileList = this.fileList.filter((item) => {
        return item.url !== res.url
      })
    },
    addColor() {
      this.colorArr.push(this.color)
      this.color = ''
    },
    addSize() {
      this.sizeArr.push(this.size)
      this.size = ''
    },
    del(val) {
      this.colorArr.splice(this.colorArr.findIndex(item => item === val), 1)
      this.checkColor.splice(this.checkColor.findIndex(item => item === val), 1)
    },
    delSize(val) {
      this.sizeArr.splice(this.sizeArr.findIndex(item => item === val), 1)
      this.checkSize.splice(this.checkSize.findIndex(item => item === val), 1)
    },
    addSku() {
      if (this.checkColor.length === 0) {
        this.$message.error('请选择颜色')
        return
      }
      if (this.checkSize.length > 0) {
        var arr = [this.checkColor, this.checkSize]
        var lastArr = arr.reduce((total, current) => {
          var newarr = []
          total.forEach(out => [
            current.forEach(inner => {
              if (typeof out === 'object') {
                newarr.push([...out, inner])
              } else {
                newarr.push([out, inner])
              }
            })
          ])
          return newarr
        })
        this.filterSkuArr(lastArr)
        return lastArr
      } else {
        this.checkColor.forEach((item) => {
          this.skuArr.push({ color: item })
        })
      }
    },
    createSku() {
      this.$confirm('此操作将清空sku列表生成新的列表, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$message.success('创建成功')
        var arr = [this.checkColor, this.checkSize]
        var lastArr = arr.reduce((total, current) => {
          var newarr = []
          total.forEach(out => [
            current.forEach(inner => {
              if (typeof out === 'object') {
                newarr.push([...out, inner])
              } else {
                newarr.push([out, inner])
              }
            })
          ])
          return newarr
        })
        this.filterSkuArr(lastArr)
        return lastArr
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    filterSkuArr(newarr) {
      newarr.forEach(item => {
        const arr = [
          { key: '颜色', value: item[0] },
          { key: '大小', value: item[1] }]
        var obj = {
          stock: '',
          lockStock: '',
          lowStock: '',
          skuCode: '',
          pic: '',
          sale: '',
          price: '',
          tempID: uuidv4()

        }
        this.skuArr.push({ ...obj, spData: arr })
      })
      console.log(this.skuArr)
    },
    // 选中当前行
    selectRow(row) {
      this.currentRow = row
    },
    handlePicSuccess(res, file) {
      if (res.success) {
        this.currentRow.pic = res.data.fileUrl
      } else {
        this.$message.error('上传图片失败')
      }
    },
    // /删除当前行
    delRow(val) {
      this.skuArr = this.skuArr.filter((item) => {
        return item.tempID !== val.tempID
      })
    },
    // 获取富文本内容
    getTin() {
      var text = this.$refs.Tin.getContent()
      return text
    },
    setTin(val) {
      this.$refs.Tin.setContent(val)
    },
    // 提交保存
    submit() {
      var brandName = ''
      var productCategoryName = ''
      this.brandList.forEach(item => {
        if (item.id === this.formInline.brandId) {
          brandName = item.name
        }
      })
      this.categoryList.forEach(item => {
        if (item.id === this.formInline.productCategoryId) {
          productCategoryName = item.name
        }
      })
      const content = this.getTin() // 获取富文本内容
      const PicsArr = this.fileList.map(item => item.url)// 上传画册图片列表
      // sku列表
      const skuArrList = []
      this.skuArr.forEach(item => {
        if (item.tempID) {
          delete item.tempID
        }
        skuArrList.push({
          ...item,
          spData: JSON.stringify(item.spData)
        })
      })

      if (this.id) {
        // 编辑
        updateProductAndSkus({
          pmsSkuStockList: skuArrList,
          product: {
            ...this.formInline,
            brandName,
            productCategoryName,
            detailMobileHtml: content,
            albumPics: PicsArr.join(','),
            serviceIds: this.serviceIds.join(',')
          }
        }).then(res => {
          if (res.success) {
            this.$message.success('编辑成功')
            this.$router.push({ name: 'ProductList' })
          } else {
            this.$message.error('编辑失败')
          }
        })
      } else {
        // 新增
        addProductAndSkus({
          pmsSkuStockList: skuArrList,
          product: {
            ...this.formInline,
            brandName,
            productCategoryName,
            detailMobileHtml: content,
            albumPics: PicsArr.join(','),
            serviceIds: this.serviceIds.join(',')
          }
        }).then(res => {
          if (res.success) {
            this.$message.success('新增成功')
            this.$router.push({ name: 'ProductList' })
          } else {
            this.$message.error('新增失败')
          }
        })
      }
    }

  }
}
</script>
<style lang="scss" scoped>
  .title{
    font-size: 16px;
    padding: 10px 0;
    margin-bottom: 30px;
    margin-top: 40px;
    border-bottom: 1px solid #e5e5e5;
  }
   .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
  }
  .avatar {
    width: 100px;
    height: 100px;
    display: block;
  }
.clearfix{
   font-size: 16px;
    padding: 10px 0;
    border-bottom: 1px solid #e5e5e5;
    margin-bottom: 30px;
}
  .sku{
    display: flex;
    align-items: center;
    justify-content: space-between;

    .sku-left{
      display: flex;
      align-items: center;
      .items{
        display: flex;
        align-items: center;
        margin-left: 10px;
        .el-button{
          margin-left: 5px;
        }
      }
    }
    .btns{
      display: flex;
      margin-left: 85px;
    }
  }

</style>
